<template>
  <el-header class="header">
    <div class="header-left">
      <el-button class="collapse-btn" link @click="$emit('toggle-collapse')">
        <el-icon>
          <Expand v-if="collapsed" />
          <Fold v-else />
        </el-icon>
      </el-button>
      <el-breadcrumb>
        <el-breadcrumb-item>管理后台</el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="header-right">
      <el-dropdown @command="handleCommand">
        <span class="user-info">
          <el-avatar size="small" :src="userAvatar" />
          <span class="username" :title="userName">{{ userName }}</span>
          <el-icon>
            <ArrowDown />
          </el-icon>
        </span>
        <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
              <!-- 仅通过 command 分发，避免 click 与 command 重复触发 -->
              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordVisible"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="0">
        <el-form-item prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="passwordLoading"
          />
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="passwordLoading"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="passwordLoading"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChangePassword" :disabled="passwordLoading">取消</el-button>
          <el-button type="primary" @click="submitChangePassword" :loading="passwordLoading">
            {{ passwordLoading ? '修改中...' : '确认修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-header>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown, Fold, Expand, Lock } from '@element-plus/icons-vue'
import { logout } from '@/utils/auth'
import { changePassword } from '@/api/user'
import { getUserAvatarInfo } from '@/api/user'
import { useUserStore } from '@/stores/user'
import tokenMonitor from '@/utils/tokenMonitor'

const props = defineProps({
  collapsed: Boolean
})
const emit = defineEmits(['toggle-collapse'])
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const userName = ref('管理员')
// 从store获取头像URL
const userAvatar = computed(() => userStore.userAvatar)

// 修改密码相关
const changePasswordVisible = ref(false)
const passwordFormRef = ref()
const passwordLoading = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else {
    callback()
  }
}

// 确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const currentPageTitle = computed(() => {
  const pathMap = {
    '/admin/dashboard': '仪表盘',
    '/admin/users': '用户管理',
    '/admin/roles': '角色管理',
    '/admin/permissions': '权限管理',
    '/admin/knowledge-bases': '知识库管理',
    '/admin/documents': '文档管理',
    '/admin/qa': '问答管理',
    '/admin/vectors': '向量管理',
    '/admin/system': '系统管理',
    '/admin/profile': '个人信息'
  }
  return pathMap[route.path] || '仪表盘'
})

onMounted(async()=>{
  let userInfo=JSON.parse(localStorage.getItem("userInfo"))
  let  {data}= await getUserAvatarInfo(userInfo.id)
  console.log(data.avatarUrl);
  const avatarUrl = `http://api-rag.monkeymeerkat.cn${data.avatarUrl}`
  // 将头像URL存储到store中
  userStore.setUserAvatar(avatarUrl)
})

const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'profile') {
    router.push('/admin/profile')
  } else if (command === 'changePassword') {
    openChangePasswordDialog()
  }
}

const openChangePasswordDialog = () => {
  changePasswordVisible.value = true
  // 重置表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  // 清除验证错误
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

const cancelChangePassword = () => {
  changePasswordVisible.value = false
}

const submitChangePassword = async () => {
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return

    passwordLoading.value = true
    
    // 获取当前用户ID
    const userInfo = JSON.parse(localStorage.getItem("userInfo"))
    if (!userInfo || !userInfo.id) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }

    const result = await changePassword(userInfo.id, {
      OldPassword: passwordForm.value.oldPassword,
      NewPassword: passwordForm.value.newPassword,
      ConfirmPassword: passwordForm.value.confirmPassword
    })

    if (result && (result.code === 200 || result.Code === 200)) {
      ElMessage.success('密码修改成功')
      changePasswordVisible.value = false
      // 清空表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      ElMessage.error(result?.message || result?.Message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error(error?.response?.data?.message || '密码修改失败，请稍后重试')
  } finally {
    passwordLoading.value = false
  }
}

const handleLogout = () => {
  // 停止token监控
  tokenMonitor.stop()
  
  // 清除认证信息
  logout()
  
  // 显示提示信息（避免与请求拦截器重复，登录页不再提示）
  if (location.pathname !== '/login') {
    ElMessage.success('已退出登录')
  }
  router.push('/login')
}
</script>

<style scoped>
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  color: #ffffff;
  position: relative;
  z-index: 5;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left :deep(.el-breadcrumb__item) {
  color: #ffffff !important;
}

.header-left :deep(.el-breadcrumb__inner) {
  color: #ffffff !important;
}

.header-left :deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.8) !important;
}

.collapse-btn {
  color: #fff;
  font-size: 20px;
  margin-right: 8px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s;
  color: #ffffff;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.1);
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  height: 48px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}
</style>
